package main

import (
	"context"
	"fmt"
	"github.com/wailsapp/wails/v2/pkg/runtime"
	"os"
	"path/filepath"
	"strings"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
}

// OpenDirectoryDialog 打开目录对话框
func (a *App) OpenDirectoryDialog() (string, error) {
	result, err := runtime.OpenDirectoryDialog(a.ctx, runtime.OpenDialogOptions{
		Title:            "选择目录",
		DefaultDirectory: ".",
	})
	return result, err
}

func (a *App) SeekFile(dir, name string) (result string, err error) {
	if dir == "" {
		err = fmt.Errorf("请选择目录")
		return
	}
	if name == "" {
		err = fmt.Errorf("请输入文件名")
		return
	}
	var arr []string
	defer func() {
		result = strings.Join(arr, "")
	}()
	err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.IsDir() {
			return nil
		}
		if strings.Contains(info.Name(), name) {
			arr = append(arr, path+"\t\n")
		}
		return nil
	})
	return
}
